package com.ruitaowang.wap;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruitaowang.core.domain.*;
import com.ruitaowang.core.utils.RedisUtil;
import com.ruitaowang.goods.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ruitaowang.account.security.LYSecurityUtil;
import com.ruitaowang.account.service.SysUserService;
import com.ruitaowang.account.service.WalletService;
import com.ruitaowang.core.utils.RandomUtils;
import com.ruitaowang.core.utils.StringUtils4RT;
import com.ruitaowang.core.utils.aliyun.SendSMSHelper;
import com.ruitaowang.core.web.BaseController;
import com.ruitaowang.core.web.MsgOut;

import tech.lingyi.wx.msg.out.TemplateData;
import tech.lingyi.wx.msg.out.TemplateItem;
import wx.wechat.service.mp.MPService;

@RestController
public class APIWapOrderController extends BaseController {

    protected final Logger LOGGER = LoggerFactory.getLogger(getClass());

    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderProdService orderProdService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private WalletService walletService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private UserProfitService userProfitService;
    @Autowired
    private LogisticsService logisticsService;
    @Autowired
    private OrderAdService orderAdService;
    @Autowired
    private UserMembersService userMembersService;
    @Autowired
    private AfterMarketService afterMarketService;
    @Autowired
    private CouponService couponService;
    @Autowired
    private ShoppingOrderService shoppingOrderService;
    @Autowired
    private ReceivingAddressService receivingAddressService;
    @Autowired
    private CompanyUserService companyUserService;
    @Autowired
    private WXUserinfoService wxUserinfoService;
    @Autowired
    private RedisUtil<String> redisUtil;
    @Value("${host.api}")
    private String host;

    @RequestMapping(value = "/api/wap/orders/get", method = RequestMethod.GET)
    public String wapFindOrderPage(OrderProd orderProd) {
        List out = new ArrayList();
        List<OrderProd> orderProds = orderProdService.select(orderProd);
        for (OrderProd o : orderProds) {
            if (orderService.selectByPK(o.getOrderId()).getPayStatus() == 1) {
                o.setRemark(orderService.selectByPK(o.getOrderId()).getOrderSn());
                out.add(o);
            }
        }
        MsgOut o = MsgOut.success(out);
        return this.renderJson(o);
    }

    @RequestMapping(value = "/api/wap/orderUpdate/get", method = RequestMethod.GET)
    public String wapFindOrderUpdate(Long prodId) {
        Map map = new HashMap();
        OrderProd orderProds = orderProdService.selectByPK(prodId);
        Order order = orderService.selectByPK(orderProds.getOrderId());
        map.put("order", order);
        map.put("orderProds", orderProds);
        MsgOut o = MsgOut.success(map);
        return this.renderJson(o);
    }

    @RequestMapping(value = "/api/wap/orderProd/update", method = RequestMethod.PUT)
    public String wapUpdateOrder(OrderProd orderProd, Byte orderStatus) {
        if (!ObjectUtils.isEmpty(orderProd)) {
            orderProdService.update(orderProd);
        }
        if (!ObjectUtils.isEmpty(orderStatus)) {
            Order order = new Order();
            order.setOrderStatus(orderStatus);
            order.setOrderId(orderProd.getOrderId());
            orderService.update(order);
        }
        orderProd.setRemark(orderStatus.toString());
        MsgOut o = MsgOut.success(orderProd);
        return this.renderJson(o);
    }

    //商户中心 分享商城收入
    @RequestMapping(value = "/api/wap/biz/orders", method = RequestMethod.GET)
    public String list4wapBiz(int rows, int page) {

        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
//        user = new SysUser();
//        user.setId(21l);
        Company company = new Company();
        company.setUserId(user.getId());
        List<Company> companyList = companyService.select(company);
        if (companyList != null && companyList.size() > 0) {
            company = companyList.get(0);
        } else {
            return this.renderJson(MsgOut.error("您还不是商家用户"));
        }

        OrderProd orderProd = new OrderProd();
        orderProd.setGoodsProviderId(company.getCompanyId());
        orderProd.setPage(page);
        orderProd.setRows(rows);
        List<OrderProd> list = orderProdService.selectForPage(orderProd);
        if (ObjectUtils.isEmpty(list)) {
            return this.renderJson(MsgOut.error("no data."));
        }
        UserProfitVO userProfitVO = null;
        SysUser user1 = null;
        Order order = null;
        List<UserProfitVO> userProfitVOs = new ArrayList<>();
        for (OrderProd up : list) {
            userProfitVO = new UserProfitVO();
            order = orderService.selectByPK(up.getOrderId());
            if (ObjectUtils.isEmpty(order)) {
                continue;
            }

            user1 = sysUserService.selectByPK(order.getUserId());
            if (!ObjectUtils.isEmpty(user1)) {
                userProfitVO.setNickname(user1.getNickname());
                userProfitVO.setHeadimgurl(user1.getHeadimgurl());
            }
            userProfitVO.setAmount(up.getGoodsScreenPrice() + up.getXpPrice());
            userProfitVO.setCtime(up.getCtime());
            userProfitVO.setUserProfit(up.getGoodsRealPrice() + up.getXpPrice());
            userProfitVOs.add(userProfitVO);
        }
        MsgOut o = MsgOut.success(userProfitVOs);

        o.setRecords(orderProd.getRecords());
        o.setTotal(orderProd.getTotal());
        return this.renderJson(o);
    }

    @RequestMapping(value = "/api/wap/orders", method = RequestMethod.GET)
    public String listForWap(Order order, String orderStatusStr) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
//        order.setOrderStatus((byte)1);

        order.setUserId(user.getId());
        List<Order> orderList = null;
        List<OrderProd> orderProdList = null;
        if (orderStatusStr != null) {

            Map<String, List> resMap = new HashMap<>();
            String[] orderStatusArray = orderStatusStr.split(",");
            for (int i = 0; i < orderStatusArray.length; i++) {

                order.setOrderStatus(Byte.parseByte(orderStatusArray[i]));
                orderList = orderService.select(order);
                orderProdList = new ArrayList<>();

                OrderProd tmp = new OrderProd();
                for (Order o : orderList) {
                    tmp.setOrderId(o.getOrderId());
                    orderProdList.addAll(orderProdService.select(tmp));
                }

            }
            resMap.put("orderList", orderList);
            resMap.put("orderProdList", orderProdList);
            MsgOut o = MsgOut.success(resMap);
            return this.renderJson(o);
        } else {
            orderList = orderService.select(order);
            orderProdList = new ArrayList<>();

            OrderProd tmp = new OrderProd();
            for (Order o : orderList) {
                tmp.setOrderId(o.getOrderId());
                orderProdList.addAll(orderProdService.select(tmp));
            }
            Map<String, List> resMap = new HashMap<>();
            resMap.put("orderList", orderList);
            resMap.put("orderProdList", orderProdList);
            MsgOut o = MsgOut.success(resMap);
            return this.renderJson(o);
        }
    }

    @RequestMapping(value = "/api/wap/rt/orders", method = RequestMethod.POST)
    public String createRTOrder(Order order, Goods goods) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        Goods g = goodsService.selectByPK(goods.getGoodsId());
        if (ObjectUtils.isEmpty(g)) {
            return this.renderJson(MsgOut.error("参数 GoodsId 错误"));
        }
        //软件支付没有订单详情  支付状态为 2
        try {
            //生成订单order
            order.setAmountMoney(g.getGoodsScreenPrice());
            order.setOrderAmount(g.getGoodsScreenPrice());
            order.setOrderSn(RandomUtils.genOrderSN(user.getId()));
            order.setGoodsPayType(g.getGoodsPayType());
            //龙蛙软件支付状态2
            order.setPayWay((byte) 4);
            order.setUserId(user.getId());
            order.setOrderType((byte)1);
            order.setPayTime(System.currentTimeMillis());
            //备注标识商品 ID
            if (StringUtils4RT.ruitaoMZGoodsId.equals(goods.getGoodsId().toString()) || StringUtils4RT.ruitaoQR6GoodsId.equals(goods.getGoodsId().toString()) || StringUtils4RT.ruitaoDPGoodsId.equals(goods.getGoodsId().toString()) || StringUtils4RT.ruitaoHDCommunity.equals(goods.getGoodsId().toString())) {
                order.setRemark(goods.getGoodsId().toString());
                //创建订单详情
                OrderProd orderProd=new OrderProd();
                Goods where=goodsService.selectByPK(goods.getGoodsId());
                BeanUtils.copyProperties(where, orderProd);
                orderProd.setOrderId(order.getOrderId());
                orderProd.setOrderType((byte)2);
                orderProdService.insert(orderProd);
            }
            //插入数据
            orderService.insert(order);
        } catch (Exception e) {
            e.printStackTrace();
        }
        MsgOut o = MsgOut.success(order);
        return this.renderJson(o);
    }

    /**
     * 商品支付订单
     * @return
     */
    @RequestMapping(value = "/api/wap/order", method = RequestMethod.POST)
    public String create(String orderJson,Integer amountMoney, String fk,Integer memberPrice,Long addressId,Integer amountScore,byte type,Integer orderAmount,byte isShare,String shareId,@RequestHeader(value="headId",required = false) String userId) {
//        SysUser user = LYSecurityUtil.currentSysUser();
        int scores = 0;
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        LOGGER.info(orderJson);
        SysUser user  = sysUserService.selectByPK(Long.parseLong(userId));

        Order order = new Order();
        //检测FK
        if(ObjectUtils.isEmpty(fk)){
            return this.renderJson(MsgOut.error());
        }
        String[] iDs = fk.split("-");
        if(ObjectUtils.isEmpty(iDs) || iDs.length < 4){
            return this.renderJson(MsgOut.error());
        }
        //查询收货地址
        ReceivingAddress receivingAddress=receivingAddressService.selectByPK(addressId);
        if(ObjectUtils.isEmpty(receivingAddress)){
            return this.renderJson(MsgOut.error("收货地址无效"));
        }
        //收货地址
        if(ObjectUtils.isEmpty(receivingAddress.getDistrict())){
            order.setShippingAddress(receivingAddress.getProvince()+receivingAddress.getCity()+" "+receivingAddress.getAddress());
        }else{
            order.setShippingAddress(receivingAddress.getProvince()+receivingAddress.getCity()+receivingAddress.getDistrict()+" "+receivingAddress.getAddress());
        }
        //order.setShippingAddress(receivingAddress.getAddress());
        order.setConsignee(receivingAddress.getUserName());
        order.setMobile(receivingAddress.getMobile());

        //计算优惠价格
        if (!ObjectUtils.isEmpty(user.getDepartment())){
            order.setMemberPrice(Integer.valueOf(user.getDepartment()));
            double a = (double)(orderAmount * Integer.valueOf(user.getDepartment())) / 100;
            if (a < 1){
                amountMoney = 1;
            }else {
                amountMoney = new Long(Math.round(a)).intValue();
            }
        }
        //订单基本信息
        order.setAmountMoney(amountMoney);
        order.setAmountScore(amountScore);
        order.setMemberPrice(memberPrice);
        order.setOrderType(type);
        order.setUserId(user.getId());
        order.setUserName(user.getNickname());
        order.setOrderSn(RandomUtils.genOrderSN(user.getId()));
        order.setOrderAmount(orderAmount);
        //晒单没有明细，暂时只走普通交易
        //order.setGoodsPayType(isShare);
        //晒单明细出来后，注掉下面一行
        order.setGoodsPayType((byte)0);
//        String[] shareIDs = shareId.split("-");
//        Long newShareId = Long.valueOf(shareIDs[2]);
        Long newShareId = 0L;
        order.setShareId(newShareId);
        orderService.insert(order);
        JSONArray objects = JSON.parseArray(orderJson);
        List<OrderProd> list = new ArrayList<>();
        if (!ObjectUtils.isEmpty(objects)){
            for (int i = 0; i < objects.size(); i++){
                ShoppingOrderVO shoppingOrderVO=JSON.parseObject(objects.get(i).toString(), ShoppingOrderVO.class);
                //检测商户
                Company company = companyService.selectByPK(shoppingOrderVO.getCompanyId());
                if (ObjectUtils.isEmpty(company)) {
                    return this.renderJson(MsgOut.error("该商户信息错误"));
                }
                //创建shopping订单
                ShoppingOrder shoppingOrder = new ShoppingOrder();
                shoppingOrder.setAmount(orderAmount);
                shoppingOrder.setOrderId(order.getOrderId());
                shoppingOrder.setCompanyName(shoppingOrderVO.getCompanyName());
                shoppingOrder.setCompanyHeadimg(shoppingOrderVO.getCompanyHeadimg());
                shoppingOrder.setCompanyId(company.getCompanyId());
                shoppingOrder.setMessage(shoppingOrderVO.getMessage());
                shoppingOrderService.insert(shoppingOrder);

                for (OrderProd orderProd:shoppingOrderVO.getGoodsList()){
                   //创建shopping订单详情
                    Goods goods=goodsService.selectByPK(orderProd.getGoodsId());
                    //形成订单后  删除购物车中商品
                    ShoppingCart shoppingCart = new ShoppingCart();
                    shoppingCart.setGoodsId(goods.getGoodsId());
                    List<ShoppingCart> shoppingCartList=shoppingCartService.select(shoppingCart);
                    if (!ObjectUtils.isEmpty(shoppingCartList)){
                        shoppingCartService.delete(shoppingCartList.get(0).getCartId());
                    }
                    BeanUtils.copyProperties(goods, orderProd);
                    orderProd.setOrderId(shoppingOrder.getId());
                    orderProd.setOrderType((byte)1);
                    orderProdService.insert(orderProd);
                    //更新库存
                    goods.setGoodsStock(goods.getGoodsStock() - orderProd.getGoodsNumber());
                    goodsService.update(goods);
                }
            }
        }
        MsgOut o = MsgOut.success(order);
        return this.renderJson(o);
    }

    /**
     * @api {get} /api/wap/selectForOrder 订单详情页
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/admin/users
     *
     * @apiName selectForOrder
     * @apiGroup Order
     *
     * @apiParam {int} page 第几页.
     * @apiParam {int} rows 每页条数
     * @apiParam {int} payStatus 支付状态
     * @apiParam {int} orderStatus 订单状态
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *    {
                "code":0,
                "data":[{
                "amountMoney":" 订单现金",
                "amountScore":"订单红包",
                "auditStatus":"审核状态",
                "auditUserId":"审核人Id",
                "companyList":[{ 订单内得商家（list）
                                "amount":"该商家订单总价",
                                "companyHeadimg":"商家头像",
                                "companyId":"商家ID",
                                "companyName":"商家名称",
                                "ctime":1545805049934,
                                "discountId":0,
                                "favorablePrice":"满减优惠券价格",
                                "goodsList":[{ 商家内得商品（list）
                                                "companyBalance":0,
                                                "companyCouponId":"商家优惠券ID",
                                                "companyCouponPrice":"商家优惠券价格",
                                                "ctime":1545805049948,
                                                "evaluate":0,
                                                "giveScore":0,
                                                "giveType":0,
                                                "goodsAttrLinkId":"",
                                                "goodsAttrValues":"",
                                                "goodsGetType":0,
                                                "goodsId":3,
                                                "goodsName":"米菲时尚随手杯MF-P342",
                                                "goodsNumber":"商品数量",
                                                "goodsPayType":0,
                                                "goodsProviderId":"归属商家id",
                                                "goodsProviderType":"归属商家类型",
                                                "goodsRealPrice":"原价 进价",
                                                "goodsScore":"商品红包价格",
                                                "goodsScreenPrice":"现价 售价",
                                                "goodsThum":"http://static.ruitaowang.com/attached/file/20170114/20170114112032_201.jpg",
                                                "logisticsId":"物流公司id",
                                                "logisticsName":"物流公司名称",
                                                "logisticsSn":"物流单号",
                                                "memberPrice":"会员价格",
                                                "mtime":1545805049948,
                                                "orderId":"购物订单ID为shopingOrderId,软件支付为goodsorderId",
                                                "orderType":"订单分类1：购物订单2：龙蛙支付",
                                                "prodId":1072,
                                                "remark":"",
                                                "rstatus":0,
                                                "selfSupport":false,
                                                "xpPrice":0
                                                },
                                ],
                                "id":106,
                                "message":"",
                                "mtime":1545805049934,
                                "orderId":"goods",
                                "orderStatus":"订单状态,0 （买家：等待卖家发货；商家：待发货）,1  （买家：商家已发货；商家：已发货）,2 （买家：确认已收获，；商家：已完成）,3 （买家：申请退货，原因；商家：买家申请退货）,4 (买家：申请退款，原因；）,5 交易关闭",
                                "payStatus":"0 未支付,1 已支付,11 红包已支付，现金未支付",
                                "remark":"",
                                "rstatus":0
                                }],
                "consignee":"微信",
                "ctime":1545805049919,
                "exPrice":"物流价格",
                "exSn":"物流单号",
                "exText":"物流名称",
                "exWay":"快递方式,0 在线支付,1 到付",
                "goodsNumber":"订单购买数量总和",
                "goodsPayType":0,
                "memberPrice":0,
                "mobile":"13439097796",
                "mtime":"待付款倒计时（分钟）",
                "orderAmount":"订单总价格",
                "orderId":"goodsid",
                "orderSn":"20181226141729919l18233",
                "orderStatus":"订单状态,0 （买家：等待卖家发货；商家：待发货）,1  （买家：商家已发货；商家：已发货）,2 （买家：确认已收获，；商家：已完成）,3 （买家：申请退货，原因；商家：买家申请退货）,4 (买家：申请退款，原因；）,5 交易关闭",
                "orderType":1,
                "payStatus":"0 未支付,1 已支付,11 红包已支付，现金未支付",
                "payTime":"付款时间",
                "payWay":0,
                "remark":"",
                "rstatus":0,
                "shippingAddress":"北京市朝阳区 微信",
                "userId":18233
                }],
                "msg":"操作成功啦",
                "records":2,
                "title":"成功",
                "total":1,
                "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/wap/selectForOrde"
     *  }
     */
    @RequestMapping(value = "/api/wap/selectForOrder", method = RequestMethod.GET)
    public String selectForOrder(Order order,int page,@RequestHeader(value="headId",required = false) Long userId){
        if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
        String orderSetUp=redisUtil.get("order_set_up");
        if (ObjectUtils.isEmpty(orderSetUp)){
            return this.renderJson(MsgOut.error("请添加订单设置"));
        }
        OrderSetUp osu=JSON.parseObject(orderSetUp,OrderSetUp.class);
        //过滤已过期order
        if (page == 1){
            Order verification= new Order();
            verification.setPage(page);
            verification.setUserId(userId);
            verification.setPayStatus((byte)0);
            List<Order> verifications=orderService.selectOrderPage(verification);
            for (Order v:verifications){
                Long sxtime = (System.currentTimeMillis()-v.getCtime());
                if(sxtime >= osu.getCancelTime() * 60 * 1000){
                    orderService.delete(v.getOrderId());
                    ShoppingOrder shoppingOrder = new ShoppingOrder();
                    shoppingOrder.setOrderId(v.getOrderId());
                    List<ShoppingOrder> shoppingOrderList = shoppingOrderService.select(shoppingOrder);
                    for (ShoppingOrder s:shoppingOrderList){
                        shoppingOrderService.delete(s.getId());
                        OrderProd orderProd = new OrderProd();
                        orderProd.setOrderId(s.getId());
                        List<OrderProd> orderProds=orderProdService.select(orderProd);
                        for (OrderProd o:orderProds){
                            Goods goods=goodsService.selectByPK(o.getGoodsId());
                            goods.setGoodsStock(goods.getGoodsStock() + o.getGoodsNumber());
                            goodsService.update(goods);
                        }
                    }
                }
            }
        }
        //查询订单
        order.setPage(page);
        order.setUserId(userId);
        List<Order> orders=orderService.selectOrderPage(order);
        //替代集合orders
        List<OrderVO> orderVOS = new ArrayList<>();
        if (!ObjectUtils.isEmpty(orders)){
            for (Order o:orders){
                int goodsNumber = 0;
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(o, orderVO);
                //替代集合shoppingOrders
                List<ShoppingOrderVO> shoppingOrderVOS= new ArrayList<>();
                ShoppingOrder shoppingOrder = new ShoppingOrder();
                shoppingOrder.setOrderId(o.getOrderId());
                List<ShoppingOrder> shoppingOrders=shoppingOrderService.select(shoppingOrder);
                if (!ObjectUtils.isEmpty(shoppingOrders)){
                    for (ShoppingOrder so:shoppingOrders){
                        ShoppingOrderVO shoppingOrderVO = new ShoppingOrderVO();
                        BeanUtils.copyProperties(so, shoppingOrderVO);
                        OrderProd orderProd = new OrderProd();
                        orderProd.setOrderId(so.getId());
                        orderProd.setOrderType((byte)1);
                        List<OrderProd> orderProds = orderProdService.select(orderProd);
                        for (OrderProd op : orderProds){
                            goodsNumber = goodsNumber + op.getGoodsNumber();
                        }
                        shoppingOrderVO.setGoodsList(orderProds);
                        shoppingOrderVOS.add(shoppingOrderVO);
                    }
                }
                orderVO.setCompanyList(shoppingOrderVOS);
                //获取订单取消时间  与 自动收货时间
                Long sxtime = System.currentTimeMillis()-orderVO.getCtime();
                if (orderVO.getPayStatus() == 0){
                    //分钟
                     Long cancelTime=osu.getCancelTime()*60*1000;
                    if(sxtime <= cancelTime){
                        sxtime = cancelTime - sxtime;
                        orderVO.setMtime(sxtime);
                    }
                }else if (orderVO.getPayStatus() == 1 && orderVO.getOrderStatus() == 1){
                    //小时
                    Long receivingGoodsTime=osu.getReceivingGoodsTime()*60*60*1000;
                    if(sxtime <= receivingGoodsTime){
                        sxtime = receivingGoodsTime - sxtime;
                        orderVO.setMtime(sxtime);
                    }else{
                        orderVO.setMtime(0L);
                        //自动确认收货
                        Order receivingGoodsOrder = orderService.selectByPK(orderVO.getOrderId());
                        receivingGoodsOrder.setOrderStatus((byte)6);
                        orderService.update(receivingGoodsOrder);
                        ShoppingOrder rgoso = new ShoppingOrder();
                        rgoso.setOrderId(orderVO.getOrderId());
                        List<ShoppingOrder> orderList=shoppingOrderService.select(rgoso);
                        if (!ObjectUtils.isEmpty(orderList)){
                            for (ShoppingOrder so:orderList){
                                so.setOrderStatus((byte) 6);
                                shoppingOrderService.update(so);
                            }
                        }
                    }
                }
                orderVO.setGoodsNumber(goodsNumber);
                orderVOS.add(orderVO);
            }
        }
        MsgOut o = MsgOut.success(orderVOS);
        o.setRecords(order.getRecords());
        o.setTotal(order.getTotal());
        return this.renderJson(o);
    }

    /**
     * 个人评价页
     * @param shoppingOrderVO
     * @param page
     * @param userId
     * @return
     */
    @RequestMapping(value = "/api/wap/selectForPj", method = RequestMethod.GET)
    public String selectForPj(ShoppingOrderVO shoppingOrderVO,int page,@RequestHeader(value="headId",required = false) Long userId){
        if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
        shoppingOrderVO.setPage(page);
        shoppingOrderVO.setUserId(userId);
        List<ShoppingOrder> shoppingOrderList = shoppingOrderService.selectForPj(shoppingOrderVO);
        List<ShoppingOrderVO> shoppingOrderVOList = new ArrayList<>();
        for(ShoppingOrder s : shoppingOrderList){
            int goodsNumber = 0;
            int totalPrice = 0;
            ShoppingOrderVO shoppingOrderVO1 = new ShoppingOrderVO();
            BeanUtils.copyProperties(s, shoppingOrderVO1);
            OrderProd orderProd = new OrderProd();
            orderProd.setOrderId(s.getId());
            orderProd.setOrderType((byte)1);
            List<OrderProd> orderProdList = orderProdService.select(orderProd);
            for(OrderProd op : orderProdList){
                goodsNumber = goodsNumber + op.getGoodsNumber();
                totalPrice += totalPrice + op.getGoodsScreenPrice() * op.getGoodsNumber() - op.getMemberPrice();
            }
            shoppingOrderVO1.setGoodsNumber(goodsNumber);
            shoppingOrderVO1.setTotalPrice(totalPrice);
            shoppingOrderVO1.setGoodsList(orderProdList);
            shoppingOrderVOList.add(shoppingOrderVO1);
        }
        MsgOut o = MsgOut.success(shoppingOrderVOList);
        o.setRecords(shoppingOrderVO.getRecords());
        o.setTotal(shoppingOrderVO.getTotal());
        return this.renderJson(o);
    }

    /**
     *  订单详情
     * @param orderId
     * @param userId
     * @return
     */
    @RequestMapping(value = "/api/wap/OrderXqq", method = RequestMethod.GET)
    public String selectForOrderXqq(Long orderId,@RequestHeader(value="headId",required = false) Long userId){
        Map map = new HashMap();
        List listOut = new ArrayList();
        Order order = orderService.selectByPK(orderId);
        ShoppingOrder shoppingOrder = new ShoppingOrder();
        shoppingOrder.setOrderId(orderId);
        List<ShoppingOrder> shoppingOrderList = shoppingOrderService.select(shoppingOrder);
        List<ShoppingOrderVO> shoppingOrderVOList = new ArrayList<>();
        for(ShoppingOrder s : shoppingOrderList){
            if (ObjectUtils.isEmpty(s.getCompanyHeadimg())) {
                s.setCompanyHeadimg("http://static.ruitaowang.com/attached/file/2018/07/18/20180718153138439.jpg");
            }
            ShoppingOrderVO shoppingOrderVO = new ShoppingOrderVO();
            BeanUtils.copyProperties(s,shoppingOrderVO);
            OrderProd orderProd = new OrderProd();
            orderProd.setOrderId(s.getId());
            orderProd.setOrderType((byte)1);
            List<OrderProd> orderProdList = orderProdService.select(orderProd);
            int totalPrice = 0;
            int memberPrice = 0;
            for(OrderProd op : orderProdList){
                totalPrice = op.getGoodsScreenPrice() * op.getGoodsNumber() - op.getMemberPrice();
                memberPrice = memberPrice + op.getMemberPrice();
            }
            shoppingOrderVO.setMemberPrice(memberPrice);
            shoppingOrderVO.setGoodsList(orderProdList);
            shoppingOrderVO.setTotalPrice(totalPrice);
            shoppingOrderVO.setCompanyPhone(companyService.selectByPK(s.getCompanyId()).getMobile());
            shoppingOrderVOList.add(shoppingOrderVO);
        }
        map.put("order",order);
        map.put("shoppingOrderList",shoppingOrderVOList);
        listOut.add(map);
        MsgOut o = MsgOut.success(listOut);
        return this.renderJson(o);
    }


    /**
     * 个人订单个数（全部，待付款，已付款）
     * @param order
     * @param userId
     * @return
     */
    @RequestMapping(value = "/api/wap/selectForOrderCount", method = RequestMethod.GET)
    public String selectForOrderCount(Order order,@RequestHeader(value="headId",required = false) Long userId){
        if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
        order.setUserId(userId);
        MsgOut o = MsgOut.success(orderService.selectOrderCount(order));
        return this.renderJson(o);
    }


    /**
     * 个人订单个数（评价）
     * @param shoppingOrderVO
     * @param userId
     * @return
     */
    @RequestMapping(value = "/api/wap/selectForPjOrderCount", method = RequestMethod.GET)
    public String selectForPjOrderCount(ShoppingOrderVO shoppingOrderVO,@RequestHeader(value="headId",required = false) Long userId){
        if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
        shoppingOrderVO.setUserId(userId);
        MsgOut o = MsgOut.success(shoppingOrderService.selectForPjCount(shoppingOrderVO));
        return this.renderJson(o);
    }


    /**
     * 商家订单个数
     * @param orderVO
     * @param userId
     * @return
     */
    @RequestMapping(value = "/api/wap/selectForOrderCompanyCount", method = RequestMethod.GET)
    public String selectForOrderCompanyCount(OrderVO orderVO,@RequestHeader(value="headId",required = false) Long userId){
        if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
        if (!ObjectUtils.isEmpty(orderVO.getPayStatus()) && orderVO.getPayStatus() == 1){
            orderVO.setOrderStatus((byte)0);
        }
        MsgOut o = MsgOut.success(orderService.selectForOrderCompanyCount(orderVO));
        return this.renderJson(o);
    }

    /**
     * 商家订单个数(新版)
     * @param shoppingOrder
     * @param userId
     * @return
     */
    @RequestMapping(value = "/api/wap/OrderCount", method = RequestMethod.GET)
    public String OrderCount(ShoppingOrder shoppingOrder,@RequestHeader(value="headId",required = false) Long userId){
        if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
        Map map = new HashMap();
        Company company  = companyService.selectByCompanyStaff(userId);
        shoppingOrder.setCompanyId(company.getCompanyId());
        shoppingOrder.setPayStatus((byte)0);
        //待付款个数
        Long waitCount = shoppingOrderService.selectForOrderCount(shoppingOrder);
        shoppingOrder.setPayStatus((byte)1);
        shoppingOrder.setOrderStatus((byte)0);
        //待发货个数
        Long waitSendCount = shoppingOrderService.selectForOrderCount(shoppingOrder);
        shoppingOrder.setPayStatus((byte)1);
        shoppingOrder.setOrderStatus((byte)1);
        //已发货个数
        Long sendCount = shoppingOrderService.selectForOrderCount(shoppingOrder);
        shoppingOrder.setPayStatus((byte)1);
        shoppingOrder.setOrderStatus((byte)3);
        //售后个数
        Long saleCount = shoppingOrderService.selectForOrderCount(shoppingOrder);
        shoppingOrder.setPayStatus((byte)1);
        shoppingOrder.setOrderStatus((byte)2);
        //已完成个数
        Long finishCount = shoppingOrderService.selectForOrderCount(shoppingOrder);

        map.put("waitCount",waitCount);
        map.put("waitSendCount",waitSendCount);
        map.put("sendCount",sendCount);
        map.put("saleCount",saleCount);
        map.put("finishCount",finishCount);

        MsgOut o = MsgOut.success(map);
        return this.renderJson(o);

    }

    /**
     *  商家订单列表
     * @param shoppingOrder
     * @param page
     * @param userId
     * @return
     */
    @RequestMapping(value = "/api/wap/selectForOrderCompany", method = RequestMethod.GET)
    public String selectForOrderCompany(ShoppingOrder shoppingOrder,int page,@RequestHeader(value="headId",required = false) Long userId){
        if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
        shoppingOrder.setPage(page);
        List<ShoppingOrder> shoppingOrders=shoppingOrderService.selectForOrder(shoppingOrder);
        List<Order> orderVOS = new ArrayList<>();
        for (ShoppingOrder so:shoppingOrders){
            OrderVO orderVO = new OrderVO();
            Order order=orderService.selectByPK(so.getOrderId());
            BeanUtils.copyProperties(order, orderVO);
            orderVO.setCompanyId(so.getCompanyId());
            List<ShoppingOrderVO> shoppingOrderList = new ArrayList<>();
            ShoppingOrderVO shoppingOrderVO = new ShoppingOrderVO();
            BeanUtils.copyProperties(so, shoppingOrderVO);
            OrderProd orderProd = new OrderProd();
            orderProd.setOrderId(so.getId());
            orderProd.setOrderType((byte)1);
            List<OrderProd> orderProds=orderProdService.select(orderProd);
            int num =0;
            for (OrderProd op:orderProds){
                num += op.getGoodsNumber();
            }
            shoppingOrderVO.setGoodsList(orderProds);
            BeanUtils.copyProperties(order, orderVO);
            shoppingOrderList.add(shoppingOrderVO);
            orderVO.setCompanyList(shoppingOrderList);
            orderVO.setGoodsNumber(num);
            orderVOS.add(orderVO);
        }
        MsgOut o = MsgOut.success(orderVOS);
        o.setRecords(shoppingOrder.getRecords());
        o.setTotal(shoppingOrder.getTotal());
        return this.renderJson(o);
    }

    /**
     * 商家订单列表（新版）
     * @param shoppingOrder
     * @param page
     * @param userId
     * @return
     */
    @RequestMapping(value = "/api/wap/orderListForCompany", method = RequestMethod.GET)
    public String orderListForCompany(ShoppingOrder shoppingOrder,int page,@RequestHeader(value="headId",required = false) Long userId){
        if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
        shoppingOrder.setPage(page);
        Long companyId = companyService.selectByCompanyStaff(userId).getCompanyId();
        shoppingOrder.setCompanyId(companyId);
        List<ShoppingOrder> shoppingOrders = shoppingOrderService.selectForOrder(shoppingOrder);
        List<ShoppingOrderVO> shoppingOrderList = new ArrayList<>();
        for (ShoppingOrder so:shoppingOrders){
            ShoppingOrderVO shoppingOrderVO = new ShoppingOrderVO();
            BeanUtils.copyProperties(so, shoppingOrderVO);
            OrderProd orderProd = new OrderProd();
            orderProd.setOrderId(so.getId());
            orderProd.setOrderType((byte)1);
            List<OrderProd> orderProds=orderProdService.select(orderProd);
            int num =0;
            for (OrderProd op:orderProds){
                num += op.getGoodsNumber();
            }
            shoppingOrderVO.setGoodsList(orderProds);
            shoppingOrderVO.setGoodsNumber(num);
            Order order = orderService.selectByPK(so.getOrderId());
            shoppingOrderVO.setConsignee(order.getConsignee());
            shoppingOrderVO.setHeadPhoto(sysUserService.selectByPK(order.getUserId()).getHeadimgurl());
            shoppingOrderVO.setOrderSn(order.getOrderSn());
            shoppingOrderVO.setMobile(order.getMobile());
            shoppingOrderVO.setShippingAddress(order.getShippingAddress());
            shoppingOrderList.add(shoppingOrderVO);
        }
        MsgOut o = MsgOut.success(shoppingOrderList);
        o.setRecords(shoppingOrder.getRecords());
        o.setTotal(shoppingOrder.getTotal());
        return this.renderJson(o);
    }

    /**
     * 订单详情（新版）
     * @param id
     * @param userId
     * @return
     */
    @RequestMapping(value = "/api/wap/orderForCompany", method = RequestMethod.GET)
    public String orderForCompany(Long id,@RequestHeader(value="headId",required = false) Long userId){
        if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
        ShoppingOrder shoppingOrder = shoppingOrderService.selectByPK(id);
        Company company = companyService.selectByPK(shoppingOrder.getCompanyId());
        ShoppingOrderVO shoppingOrderVO = new ShoppingOrderVO();
        BeanUtils.copyProperties(shoppingOrder, shoppingOrderVO);
        OrderProd orderProd = new OrderProd();
        orderProd.setOrderId(shoppingOrderVO.getId());
        orderProd.setOrderType((byte)1);
        List<OrderProd> orderProds=orderProdService.select(orderProd);
        int num =0;
        for (OrderProd op:orderProds){
            num += op.getGoodsNumber();
        }
        shoppingOrderVO.setGoodsList(orderProds);
        shoppingOrderVO.setGoodsNumber(num);
        Order order = orderService.selectByPK(shoppingOrder.getOrderId());
        shoppingOrderVO.setConsignee(order.getConsignee());
        shoppingOrderVO.setHeadPhoto(sysUserService.selectByPK(order.getUserId()).getHeadimgurl());
        shoppingOrderVO.setOrderSn(order.getOrderSn());
        shoppingOrderVO.setMobile(order.getMobile());
        shoppingOrderVO.setShippingAddress(order.getShippingAddress());
        shoppingOrderVO.setPayTime(order.getPayTime());
        shoppingOrderVO.setLinkman(sysUserService.selectByPK(userId).getNickname());
        shoppingOrderVO.setDefaultLogistics(company.getDefaultLogistics());
        MsgOut o = MsgOut.success(shoppingOrderVO);
        return this.renderJson(o);
    }

    /**
     *  商家评价页
     * @param shoppingOrder
     * @param page
     * @param userId
     * @return
     */
    @RequestMapping(value = "/api/wap/selectForCompanyPj", method = RequestMethod.GET)
    public String selectForCompanyPj(ShoppingOrder shoppingOrder,int page,@RequestHeader(value="headId",required = false) Long userId){
        if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
        shoppingOrder.setPage(page);
        List<ShoppingOrder> shoppingOrderList = shoppingOrderService.selectForCompanyPj(shoppingOrder);
        List<ShoppingOrder> shoppingOrders = new ArrayList<>();
        for(ShoppingOrder s : shoppingOrderList){
            ShoppingOrderVO shoppingOrderVO = new ShoppingOrderVO();
            BeanUtils.copyProperties(s, shoppingOrderVO);
            OrderProd orderProd = new OrderProd();
            orderProd.setOrderId(s.getId());
            orderProd.setOrderType((byte)1);
            List<OrderProd> orderProds = orderProdService.select(orderProd);
            shoppingOrderVO.setGoodsList(orderProds);
            shoppingOrders.add(shoppingOrderVO);
        }
        MsgOut o = MsgOut.success(shoppingOrders);
        o.setRecords(shoppingOrder.getRecords());
        o.setTotal(shoppingOrder.getTotal());
        return this.renderJson(o);
    }

    /**
     * 购物车支付成功后详情
     * @param orderId
     * @param userId
     * @return
     */
    @RequestMapping(value = "/api/wap/paymentSuccess", method = RequestMethod.GET)
    public String paymentSuccess(Long orderId,@RequestHeader(value="headId",required = false) Long userId){
        if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
        List listOut = new ArrayList();
        Order order = orderService.selectByPK(orderId);
        Order order1 = new Order();
        order1.setOrderType(order.getOrderType());
        order1.setOrderAmount(order.getOrderAmount());
        listOut.add(order1);
        //购买者的推送消息
        if(order.getPayStatus() == 1 && order.getPushId() == 0){
            buildQRNotify(order.getUserId(),(long)0,orderId,1,0);
        }
        ShoppingOrder shoppingOrder = new ShoppingOrder();
        shoppingOrder.setOrderId(orderId);
        List<ShoppingOrder> shoppingOrderList = shoppingOrderService.select(shoppingOrder);
        //店铺的推送消息
        if(order.getPayStatus() == 1 && order.getPushId() == 0){
            for(ShoppingOrder s : shoppingOrderList){
                buildQRNotify(order.getUserId(),companyService.selectByPK(s.getCompanyId()).getUserId(),orderId,2,s.getAmount());
                String phone = sysUserService.selectByPK(companyService.selectByPK(s.getCompanyId()).getUserId()).getPhone();
                LOGGER.info("phone == " + phone);
                try {
                    SendSMSHelper.sendOrder(phone, "买家已付款");
                } catch (Exception e) {
                    e.printStackTrace();
                    return this.renderJson(MsgOut.error("发送短信异常"));
                }
                CompanyUser companyUser = new CompanyUser();
                companyUser.setCompanyId(s.getCompanyId());
                companyUser.setUserId(Long.valueOf(userId));
                List<CompanyUser> companyUserList = companyUserService.select(companyUser);
                if (ObjectUtils.isEmpty(companyUserList)){
                    companyUserService.insert(companyUser);
                }
            }
            Order order2 = new Order();
            order2.setOrderId(orderId);
            order2.setPushId((byte)1);
            orderService.update(order2);
        }

        MsgOut o = MsgOut.success(listOut);
        return this.renderJson(o);
    }

    /**
     * 订单更新
     * @param shoppingOrder
     * @param userId
     * @return
     */
    @RequestMapping(value = "/api/wap/updateShoppingOrder", method = RequestMethod.PUT)
    public String updateOrder(ShoppingOrder shoppingOrder,@RequestHeader(value="headId",required = false) Long userId){
        if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
        if (ObjectUtils.isEmpty(shoppingOrder)){
            return this.renderJson(MsgOut.error("参数错误"));
        }
        shoppingOrderService.update(shoppingOrder);
        if(!ObjectUtils.isEmpty(shoppingOrder.getOrderStatus())){
            Order order = new Order();
            ShoppingOrder shoppingOrder1 = shoppingOrderService.selectByPK(shoppingOrder.getId());
            order.setOrderId(shoppingOrder1.getOrderId());
            order.setOrderStatus(shoppingOrder.getOrderStatus());
            orderService.update(order);
        }
        MsgOut o = MsgOut.success(shoppingOrder);
        return this.renderJson(o);
    }

    /**
     *  删除订单
     * @param orderId
     * @param userId
     * @return
     */
    @RequestMapping(value = "/api/wap/deleteShoppingOrder/{orderId}", method = RequestMethod.DELETE)
    public String deleteOrder(@PathVariable("orderId")Long orderId,@RequestHeader(value="headId",required = false) Long userId){
        if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
        orderService.delete(orderId);
        MsgOut o = MsgOut.success("操作成功！");
        return this.renderJson(o);
    }

    /**
     * 确认收货推送消息
     * @param userId
     * @param companyId
     * @param orderId
     * @param type
     */
//    public void buildSoNotify(Long userId,Long companyId,Long orderId,int type) {
//        TemplateData templateData = TemplateData.New();
//        SNSWXUserinfo snswxUserinfo;
//        if(type == 1){
//            snswxUserinfo = wxUserinfoService.selectByPK(userId);
//        } else {
//            snswxUserinfo = wxUserinfoService.selectByPK(companyId);
//        }
//        if (ObjectUtils.isEmpty(snswxUserinfo)) {
//            return;
//        }
//        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
//        String date =  df.format(new Date());
//        templateData.setTouser(snswxUserinfo.getOpenid());
//        templateData.setTemplate_id("NVgrrXuVLlgC3vY80Z8SjiBaF2uONKvtXgHK1N4l2l4");
//        templateData.setTopcolor("FF0000");
//        templateData.setData(new TemplateItem());
//        if(type == 1){
//            templateData.add("first", "恭喜您下单成功！祝您购物愉快！", "#173177");
//            templateData.add("remark", "您好，您的订单已下单成功，商家会尽快安排发货，请耐心等待！", "#FF3333");
//        } else if(type == 2){
//            templateData.add("first", "来新订单啦，请你尽快发货，祝您生意兴隆！", "#173177");
//        }
//        templateData.setUrl(host + "/wap/wx/login?fk=1-35-0-0");
//        templateData.add("keyword1", sysUserService.selectByPK(userId).getNickname(), "#0044BB");
//        templateData.add("keyword2", String.valueOf(orderService.selectByPK(orderId).getAmountMoney()), "#0044BB");
//        templateData.add("keyword3", date, "#0044BB");
//        try {
//            new MPService().sendAPIEnter4TemplateMsg(templateData);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }


    /**
     * 用户下单推送消息（包含店铺）
     * @param userId
     * @param companyId
     * @param orderId
     * @param type
     */
    private void buildQRNotify(Long userId,Long companyId,Long orderId,int type,int shoppingAmount) {
        TemplateData templateData = TemplateData.New();
        SNSWXUserinfo snswxUserinfo = null;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String date =  df.format(new Date());
        if(companyId == 13){
            int[] users = {65446,13};
            for(int i = 0;i < users.length;i++){
                templateData = TemplateData.New();
                snswxUserinfo = wxUserinfoService.selectByPK((long)users[i]);
                if (ObjectUtils.isEmpty(snswxUserinfo)) {
                    return;
                }
                templateData.setTouser(snswxUserinfo.getOpenid());
                templateData.setTemplate_id("NVgrrXuVLlgC3vY80Z8SjiBaF2uONKvtXgHK1N4l2l4");
                templateData.setTopcolor("FF0000");
                templateData.setData(new TemplateItem());
                templateData.add("first", "来新订单啦，请你尽快发货，祝您生意兴隆！", "#173177");
                templateData.setUrl(host + "/wap/wx/login?fk=1-35-0-0");
                templateData.add("keyword1", sysUserService.selectByPK(userId).getNickname(), "#0044BB");
                templateData.add("keyword2", String.valueOf(shoppingAmount * 0.01), "#0044BB");
                templateData.add("keyword3", date, "#0044BB");
                try {
                    new MPService().sendAPIEnter4TemplateMsg(templateData);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else if(type == 1){
            snswxUserinfo = wxUserinfoService.selectByPK(userId);
            if (ObjectUtils.isEmpty(snswxUserinfo)) {
                return;
            }
            templateData.setTouser(snswxUserinfo.getOpenid());
            templateData.setTemplate_id("NVgrrXuVLlgC3vY80Z8SjiBaF2uONKvtXgHK1N4l2l4");
            templateData.setTopcolor("FF0000");
            templateData.setData(new TemplateItem());
            if(type == 1){
                templateData.add("first", "恭喜您下单成功！祝您购物愉快！", "#173177");
                templateData.add("remark", "您好，您的订单已下单成功，商家会尽快安排发货，请耐心等待！", "#FF3333");
            } else if(type == 2){
                templateData.add("first", "来新订单啦，请你尽快发货，祝您生意兴隆！", "#173177");
            }
            templateData.setUrl(host + "/wap/wx/login?fk=1-35-0-0");
            templateData.add("keyword1", sysUserService.selectByPK(userId).getNickname(), "#0044BB");
            templateData.add("keyword2", String.valueOf(orderService.selectByPK(orderId).getOrderAmount() * 0.01), "#0044BB");
            templateData.add("keyword3", date, "#0044BB");
            try {
                new MPService().sendAPIEnter4TemplateMsg(templateData);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if(type == 2 && companyId != 13) {
            templateData = TemplateData.New();
            snswxUserinfo = wxUserinfoService.selectByPK(companyId);
            if (ObjectUtils.isEmpty(snswxUserinfo)) {
                return;
            }
            templateData.setTouser(snswxUserinfo.getOpenid());
            templateData.setTemplate_id("NVgrrXuVLlgC3vY80Z8SjiBaF2uONKvtXgHK1N4l2l4");
            templateData.setTopcolor("FF0000");
            templateData.setData(new TemplateItem());
            templateData.add("first", "来新订单啦，请你尽快发货，祝您生意兴隆！", "#173177");
            templateData.setUrl(host + "/wap/wx/login?fk=1-35-0-0");
            templateData.add("keyword1", sysUserService.selectByPK(userId).getNickname(), "#0044BB");
            templateData.add("keyword2", String.valueOf(shoppingAmount * 0.01), "#0044BB");
            templateData.add("keyword3", date, "#0044BB");
            try {
                new MPService().sendAPIEnter4TemplateMsg(templateData);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
